#include<iostream>
#include<boost/asio.hpp>
#include<boost/crc.hpp>
#include<thread>
#include<chrono>
using namespace std;
using namespace boost::asio;
//crc转换函数
uint16_t cal_crc(const std::string & data){
    boost ::crc_16_type crc;
    crc.process_bytes(data.data(),data.size());
    return crc.checksum();
}
void receive_data(serial_port &p){
    while(true)//构建数据包
    {
        char start_byte;
        //缓冲区
        boost::asio::read(p,buffer(&start_byte,1));
        if(start_byte=='\x02'){
            char length_byte;
            boost::asio::read(p,buffer(&length_byte,1));
            int length=static_cast<unsigned char>(length_byte);
            std::string data(length,'\0');
            boost::asio::read(p,buffer(&data[0],length));
            uint16_t received_crc;
            boost::asio::read(p,buffer(&received_crc,2));
            uint16_t calculated_crc=cal_crc(data);
            if(received_crc==calculated_crc){
                std::cout<<"received data:"<<data;
            }else{//验证
                std::cout<<"crc mismatch"<<std::endl;
            }
        }

}}
int main(){
    io_service io;
    serial_port p(io,"/dev/ttyUSB0");
    p.set_option(serial_port_base::baud_rate(9600));
    receive_data(p);
    return 0;
}